// 此文件拓展兼容 vue2 一些方法

export function mapStores(...stores) {
	if (Array.isArray(stores[0])) {
		stores = stores[0]
	}
	return stores.reduce((reduced, useStore) => {
		reduced[useStore.$id + 'Store'] = function () {
			return useStore() // 指行 useStore 获取对应 store
		}
		return reduced
	}, {})
}


export function mapState(useStore, keysOrMapper) {
	return Array.isArray(keysOrMapper)
		? keysOrMapper.reduce((reduced, key) => {
			// 当传入数组时处理(常用)
			reduced[key] = function () {
				return useStore()[key]  // 获取 store 中对应状态
			}
			return reduced
		}, {})
		: Object.keys(keysOrMapper).reduce((reduced, key) => {
			// 传入一个对象时处理
			reduced[key] = function () {
				const store = useStore(); // store 数据
				const storeKey = keysOrMapper[key];
				// storekey 可能为函数
				return typeof storeKey === "function"
					? storeKey.call(this, store) // 当是函数是获取函数返回值
					: store[storeKey];
			};
			return reduced;
		}, {});
	// 注意最后返回对象形式为 { xx: function(){} }
}

export function mapActions(useStore, keysOrMapper) {
	return Array.isArray(keysOrMapper)
		? keysOrMapper.reduce((reduced, key) => {
			reduced[key] = function (...args) {
				return useStore()[key](...args)
			}
			return reduced
		}, {})
		: Object.keys(keysOrMapper).reduce((reduced, key) => {
			reduced[key] = function (...args) {
				return useStore()[keysOrMapper[key]](...args)
			}
			return reduced
		}, {})
}

export function mapWritableState(useStore, keysOrMapper) {
	return Array.isArray(keysOrMapper)
		? keysOrMapper.reduce((reduced, key) => {
			reduced[key] = {
				get() {
					return useStore()[key]
				},
				set(value) {
					return useStore()[key] = value
				},
			}
			return reduced
		}, {})
		: Object.keys(keysOrMapper).reduce((reduced, key) => {
			reduced[key] = {
				get() {
					return useStore()[keysOrMapper[key]]
				},
				set(value) {
					return useStore()[keysOrMapper[key]] = value
				},
			}
			return reduced
		}, {})
}